package cn.sofwin.web.blog.service.impl;

import cn.sofwin.core.dao.BaseDao;
import cn.sofwin.core.service.impl.BaseServiceImpl;
import cn.sofwin.web.blog.dao.UserDao;
import cn.sofwin.web.blog.entity.User;
import cn.sofwin.web.blog.service.UserService;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;

/**
 * 用户服务接口的实现
 * @author ZX
 * @version 1.0
 */
public class UserServiceImpl extends BaseServiceImpl<User> implements UserService {
    /** 用户数据访问对象 */
    private UserDao userDao = new UserDao();

    /** 私有的实例对象，用户实现单例模式 */
    private static UserServiceImpl userService = new UserServiceImpl();

    /**
     * 将构造方法设为私有，用于实现单例模式
     */
    private UserServiceImpl(){
        super();
    }

    /**
     * 对外提供的静态方法，用于获取服务实例
     * @return
     */
    public static UserService getInstance(){
        return userService;
    }


    @Override
    protected BaseDao<User> getDao() {
        return userDao;
    }


    @Override
    public User register(String username, String password, String nickname) {
        User user=userDao.selectByUsername(username);

        //用户名已经存在，注册不成功
        if (user!=null){
            return null;
        }
        // 创建用户对象
        user = new User();
        user.setUsername(username);
        user.setPassword(DigestUtils.md5Hex(password));
        user.setNickname(nickname);
        user.setGender(0);

        // 保存到数据库
        int id = userDao.insert(user);
        user.setId(id);

        return user;


    }

    @Override
    public User login(String username, String password) {
        User user=userDao.selectByUsername(username);
        //用户名不存在，登录直接失败
        if (user==null){
            return null;
        }
        password=DigestUtils.md5Hex(password);
        System.out.println(password);
        System.out.println(user.getPassword().equals(password));
        //密码不匹配，将user置空，代表登录失败
        if (!user.getPassword().equals(password)){
            user=null;
        }

        return user;
    }

    @Override
    public void updateProfile(User user, String password, String nickname, String avatar) {
        if (StringUtils.isNoneBlank(password)){
            password=DigestUtils.md5Hex(password);
            user.setPassword(password);
        }

        user.setNickname(nickname);
        user.setAvatar(avatar);
        userDao.update(user);
    }

    @Override
    public User findByUsername(String username) {
        return userDao.selectByUsername(username);
    }
}
